package com.sm.honkon.ui.fragment.signuse

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.lifecycle.observe
import com.sm.honkon.R
import com.sm.honkon.app.base.BaseFragment
import com.sm.honkon.app.ext.goBackHome
import com.sm.honkon.app.ext.goMannger
import com.sm.honkon.databinding.FrgSignUseBinding
import com.sm.honkon.ui.adapter.HandlerAdapter
import com.sm.honkon.ui.model.SignUseViewModel
import kotlinx.android.synthetic.main.frg_sign_use.*
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

class SignUseFragment : BaseFragment<SignUseViewModel, FrgSignUseBinding>() {
    override fun layoutId(): Int = R.layout.frg_sign_use

    val adapter by lazy {
        HandlerAdapter().apply {
            addChildClickViewIds(R.id.tv_edit)
            setOnItemClickListener { adapter, view, position ->
                checkList[position] = checkList[position].not()
                notifyDataSetChanged()
            }
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.tv_edit -> {
                        nav().navigateAction(
                            R.id.action_signUseFragment_to_addHandleFragment,
                            bundleOf("handler" to data[position])
                        )
                    }
                }
            }
        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.click = Click()
        tv_del.setOnClickListener {
            val data = adapter.data.filterIndexed { index, handlerEntity ->
                adapter.checkList[index]
            }
            adapter.checkList.clear()
            mViewModel.delHandlers(data)

        }
        recycler_view.apply {
            adapter = this@SignUseFragment.adapter
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.data.observe(this) {
            adapter.checkList.addAll(it.mapIndexed { index, _ ->
                adapter.checkList.getOrElse(index) { false }
            })
            adapter.setNewInstance(it.toMutableList())
        }
    }
    inner class Click {
        fun add() {
            nav().navigateAction(R.id.action_signUseFragment_to_addHandleFragment)
        }

        fun back() {
            nav().navigateUp()
        }

        fun home(){
            nav().goBackHome()
        }
        fun mannger(){

            nav().goMannger()
        }
        fun exit() {
            System.exit(0)
        }

        fun setting() {
            nav().navigate(R.id.settingFragment)
        }
    }
}